﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSH.Common.Helpers;
using System.Timers;
using NHibernate;
using NHibernate.Linq;
using MSH.Common.Business;

namespace MSH.TaskServer.Tasks
{
    /// <summary>
    /// Taak die verantwoordelijk is voor het verwijderen van verlopen activatiecodes, verwijderen van niet geactiveerde users na bepaalde tijd
    /// </summary>
    public class UserManagementTask
    {
        private System.Timers.Timer timer;
        private Double maxDaysUserNotActivated = 0;

        public UserManagementTask()
        {
            /* Configuratie laden */
            Double.TryParse(System.Configuration.ConfigurationManager.AppSettings["maxDaysUserNotActivated"].ToString(), out maxDaysUserNotActivated);

            timer = new System.Timers.Timer(int.Parse(System.Configuration.ConfigurationManager.AppSettings["userManagementTaskInterval"].ToString()));
            timer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
            timer.Enabled = true;

            LogHelper.LogMessage(String.Format("UserManagementTask(): task scheduled (interval = {0} minutes)",timer.Interval/1000/60));

            OnTimedEvent(null, null);
        }

        private void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            LogHelper.LogMessage("UserManagementTask.OnTimedEvent()");
            

            //Activatiecode
            using (ISession session = NHibernateHelper.GetSessionFactory().OpenSession())
            {

                IList<User> resultList = session.Query<User>()
                                                .Where(u => u.Activated == false)
                                                .ToList<User>();

                foreach (User user in resultList)
                {
                    //User nog niet geactiveerd na 15 dagen, dus user verwijderen.
                    if (user.RegisteredTimestamp < DateTime.UtcNow.AddDays(maxDaysUserNotActivated == 0 ? -15 : (0 - maxDaysUserNotActivated)))
                    {
                        LogHelper.LogMessage("UserManagementTask: user '{0}' deleted, because the account was not activated within {1} days.", user.Username, maxDaysUserNotActivated == 0 ? 15 : maxDaysUserNotActivated);
                        session.Delete(user);
                    }
                    //Validatiecode van de user is ouder dan 5 dagen, verwijder code.
                    else if (user.UserActivation != null && user.UserActivation.ExpireTimestamp < DateTime.UtcNow)
                    {
                        LogHelper.LogMessage("UserManagementTask: activation code from user '{0}' has been expired and deleted.", user.Username);
                        UserActivation ua = user.UserActivation;
                        user.UserActivation = null;
                        session.Delete(ua);
                    }

                    using (ITransaction trans = session.BeginTransaction())
                    {
                        trans.Commit();
                    }
                }

                //Sessies
                IList<UserSession> userSessions = session.Query<UserSession>()
                                                         .Where<UserSession>(u => DateTime.UtcNow > u.ExpirationTimestamp)
                                                         .ToList<UserSession>();

                foreach (UserSession userSession in userSessions)
                {
                    LogHelper.LogMessage("UserManagementTask: session from user '{0}' has been expired and deleted.", userSession.Username);
                    session.Delete(userSession);
                }

                using (ITransaction trans = session.BeginTransaction())
                {
                    trans.Commit();
                }
            }

            LogHelper.LogMessage("UserManagementTask.OnTimedEvent(): Done");

        }
    }
}
